﻿using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Reader.Models;
using Reader.Utils;

namespace Reader.Controllers;

public class HomeCategoryBooksModel
{
    public List<Book> Books { get; set; }
    public BookCategory BookCategory { get; set; }
}

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private IWebHostEnvironment _environment;
    private readonly ApplicationDbContext _context;

    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment, ApplicationDbContext context)
    {
        _logger = logger;
        _environment = environment;
        _context = context;
    }

    public IActionResult Index()
    {
        // 最多阅读
        List<Book> hotelBooks = _context.Books.Include(e => e.Category).OrderByDescending(e => e.ReadCount).Take(8).ToList();
        ViewData["hot"] = hotelBooks;
        // 下面是一些分类
        int[] categorys = {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 41, 42};
        List<HomeCategoryBooksModel> categoryBooksModels = new List<HomeCategoryBooksModel>();
        foreach (var cid in categorys)
        {
            HomeCategoryBooksModel cm = new HomeCategoryBooksModel();
            cm.BookCategory = _context.Categories.Where(e => e.Id == cid).First();
            cm.Books = _context.Books.Where(e => e.CategoryId == cid).OrderByDescending(e => e.ReadCount).Take(8).ToList();
            categoryBooksModels.Add(cm);
        }
        ViewData["category_books"] = categoryBooksModels;
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

    [HttpPost]
    public async Task<IActionResult> UploadFiles(IFormFile file)
    {
        string path = await FileHelper.SaveFileAsync(file, _environment);
        return Json(new
        {
            AbsPath = Path.Combine(_environment.WebRootPath, path),
            Path = path
        });
    }
}